var util = require('../../utils/util.js');
const app = getApp();
Page({
  data: {
    movies: [],
    inTheaters: {},
    comingSoon: {},
    top250: {},
    searchResult: {},
    containerShow: true,
    searchPanelShow: false,
    searchPanelShow: {}
  },
  onLoad: function (event) {
    var inTheatersUrl = app.globalData.doubanBase + '/v2/movie/in_theaters' + '?start=0&count=3';
    var comingSoonUrl = app.globalData.doubanBase + '/v2/movie/coming_soon' + '?start=0&count=3';
    var top250Url = app.globalData.doubanBase + '/v2/movie/top250' + '?start=0&count=3';
    this.getMovieListData(inTheatersUrl, "inTheaters", "正在热映");
    this.getMovieListData(comingSoonUrl, 'comingSoon', "即将上映");
    this.getMovieListData(top250Url, 'top250', "豆瓣Top250");
  },
  // 发起网络请求
  getMovieListData: function (url, key, categoryTitle) {
    var that = this;
    wx.request({
      url: url,
      header: {
        "Content-Type": "application/xml"
      },
      method: 'GET',
      success: function (res) {
        //console.log(res);
        that.processDoubanData(res.data, key, categoryTitle)
      },
      fail: function (res) {
        console.log(res);
      }
    })
  },
  // 处理返回的数据
  processDoubanData: function (moviesDouban, key, categoryTitle) {
    var movies = [];
    for (var idx in moviesDouban.subjects) {
      var subject = moviesDouban.subjects[idx];
      var title = subject.title;
      if (title.length >= 6) {
        title = title.substring(0, 6) + '...';
      }
      var temp = {
        stars: util.convertToStarsArray(subject.rating.stars),
        title: title,
        average: subject.rating.average,
        converageUrl: subject.images.large,
        movieId: subject.id
      }
      movies.push(temp);
    }
    // 动态增加属性，并赋值
    var readyData = {};
    //console.log(movies);
    readyData[key] = {
      movies: movies,
      categoryTitle: categoryTitle
    };
    this.setData(readyData)
  },
  onMoreTap: function (event) {
    var category = event.currentTarget.dataset.category;
    wx.navigateTo({
      url: 'more-movie/more-movie?category=' + category,
    })
  },
  onBindFocus: function (event) {
    this.setData({
      containerShow: false,
      searchPanelShow: true
    })
  },
  onCancelImgTap: function () {
    this.setData({
      containerShow: true,
      searchPanelShow: false,
      searchResult: {}
    })
  },
  onBindsBlur: function (event) {
    var text = event.detail.value;
    var searchUrl = app.globalData.doubanBase + "/v2/movie/search?q=" + text;
    this.getMovieListData(searchUrl, "searchResult", null);
  },
  //跳转到电影详情
  onMovieTap: function (event) {
    var movieId = event.currentTarget.dataset.movieId;
    wx.navigateTo({
      url: 'movie-detail/movie-detail?id=' + movieId
    })
  }
})